package models

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"time"
)

var pool *redis.Pool

func Init() {
	// 连接SQL
	dbhost := beego.AppConfig.String("dbHost")
	dbport := beego.AppConfig.String("dbPort")
	dbuser := beego.AppConfig.String("dbUser")
	dbpassword := beego.AppConfig.String("dbPassword")
	dbname := beego.AppConfig.String("dbName")
	if dbport == "" {
		dbport = "3306"
	}
	dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8&loc=Asia%2FShanghai"
	orm.RegisterDataBase("default", "mysql", dsn)
	orm.RegisterModel(new(User), new(Blog), new(Type), new(Label), new(FriendLink), new(DirectLink), new(Tag), new(LeaveWord), new(LeaveWordTwo))
	// 自动生成数据库表但是不修改其中的数据，同时在控制台打印日志
	_ = orm.RunSyncdb("default", false, true)
	//打印sql语句
	//orm.Debug = true
}

func init() {
	//连接NoSQL
	server := beego.AppConfig.String("redis_addr")
	password := beego.AppConfig.String("redis_password")
	pool = &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}
			if password != "" {
				_, err := c.Do("AUTH", password)
				if err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

// TableName 返回有前缀的表名
func TableName(str string) string {
	return beego.AppConfig.String("dbprefix") + str
}

// Conn 返回redis连接.
func Conn() redis.Conn {
	return pool.Get()
}
